//
//  NSString+Category.m
//  CountryLogistics
//
//  Created by Mom on 2017/3/30.
//  Copyright © 2017年 KuBaoInternet. All rights reserved.
//

#import "NSString+Category.h"
#import <CoreText/CoreText.h>

@implementation NSString (Category)

//  得到字符串的宽度
+(CGFloat)getStringWidthFromeString:(NSString *)strings height:(CGFloat)heights font:(UIFont*)fonts
{
    return  [strings boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, heights) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:fonts} context:nil].size.width;
}

+(CGFloat)getStringHeightFromeString:(NSString *)strings width:(CGFloat)widths font:(UIFont*)fonts
{
    return [strings boundingRectWithSize:CGSizeMake(widths, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:fonts} context:nil].size.height;
}

//  得到字符串的高度
+(float)getStrAttHeight:(NSString *)aTip width:(CGFloat)aWidth font:(CGFloat)aFont
{
    if(!aTip)
    {
        return 0.0f;
    }
    //  去掉空行
    NSString *myString = [aTip stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    //  创建AttributeString
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:aTip];
    
    UIFont * font = [UIFont systemFontOfSize:aFont];
    
    CTFontRef helveticaBold = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL);
    
    [attributedString addAttribute:(id)kCTFontAttributeName value:(__bridge id)helveticaBold range:NSMakeRange(0,[myString length])];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    
    [paragraphStyle setLineSpacing:5];
    
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [myString length])];
    
    CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(aWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
    
    return rect.size.height;
}

//  设置行间距
+(NSMutableAttributedString *)setLineSpacingWith:(NSString *)str
{
    if(!str)
    {
        return nil;
    }
    //  去掉空行
    NSString *myString = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:myString];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [myString length])];
    
    return attributedString;
}

/**
 *  去掉 数字 字符串后面所有的0
 *
 */
+ (NSString *)getNoZeroSuffixStringWith:(NSString *)str {
    
    for (int i = 0; i < str.length; i++) {
        
        BOOL hasZero = [str hasSuffix:@"0"];
        
        if (hasZero) {
            
            str = [str substringToIndex:str.length-1];
        }
        
        NSArray *array = [str componentsSeparatedByString:@"."];
        
        if ([[array lastObject] length] == 2) {
            
            return str;
            
        }
    }
    
    return str;
}
//时间戳转时间
+(NSString*)TimeFromTimeString:(NSString*)timeStr andFormat:(NSString*)format
{
    //取出返回的时间戳数据，设置时间格式
    NSDate *star = [NSDate dateWithTimeIntervalSince1970:[timeStr integerValue]];
    NSDateFormatter * formatter =[[NSDateFormatter alloc]init];
    [formatter setDateFormat:format];//@"yyyy-MM-dd H:mm:ss"
    NSString * string = [formatter stringFromDate:star];
    return string;
}
+ (NSDate*)timeStringFromShowTimeSting:(NSString*)timeStr fromFormat:(NSString*)fromFormats
{
    NSDateFormatter * formatter =[[NSDateFormatter alloc]init];
    
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [formatter setDateFormat:fromFormats];
    NSDate *date = [formatter dateFromString:timeStr];
    
    return date;
}
+ (NSString*)stringFromDate:(NSDate*)dates fromFormat:(NSString*)fromFormats
{
    NSDateFormatter * formatter =[[NSDateFormatter alloc]init];
    [formatter setDateFormat:fromFormats];//@"yyyy-MM-dd H:mm:ss"
    NSString * string = [formatter stringFromDate:dates];
    return string;
}
//时间转时间戳
+(NSString*)timeToTimeString
{
    NSDate *star = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[star timeIntervalSince1970]];
    return timeSp;
}
//时间字符串转时间戳(timeStr和formats格式一样才行)
+(NSString*)timeStrFromShowTimeSting:(NSString*)timeStr format:(NSString*)formats
{
    NSDateFormatter * formatter =[[NSDateFormatter alloc]init];
    [formatter setDateFormat:formats];
    NSDate *date = [formatter dateFromString:timeStr];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    return timeSp;
}

#pragma mark 清空字符串中的空白字符
+ (NSString *)DeleteSpaceStringFromStr:(NSString *)string
{
    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

// 将字典或者数组转化为JSON串
+ (NSString *)FromDataToJSString:(id)theData{
    if ([theData isEqual:[NSNull null]] || !theData) {
        theData = [[NSMutableArray alloc] init];
    }
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    if ([jsonData length] > 0 && error == nil){
        return [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        return nil;
    }
}

//拼接数字成字符串
+ (NSString *)FromArraryToString:(NSArray *)arry
{
    NSString *string=@"";
    for (int i = 0; i < arry.count; i++) {
        if (string.length==0) {
            string=arry[i];
        }
        else
        {
            string=[NSString stringWithFormat:@"%@%@",string,arry[i]];
        }
    }
    return string;
}

+ (NSString *)FromArraryToString:(NSMutableArray *)arry linkString:(NSString*)linkStr
{
    NSString *string=@"";
    for (int i = 0; i < arry.count; i++) {
        if (string.length==0) {
            string=arry[i];
        }
        else
        {
            string=[NSString stringWithFormat:@"%@%@%@",string,linkStr,arry[i]];
        }
    }
    return string;
}

+ (NSString*)phoneNumber:(NSString*)phone
{
    NSString * show = [phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    return show;
}

+ (NSString*) getSecrectStringWithBankNo:(NSString *)BankNo
{
    NSMutableString *newStr = [NSMutableString stringWithString:BankNo];
    
    NSRange range = NSMakeRange(0, 12);
    
    if (newStr.length>12) {
        
        [newStr replaceCharactersInRange:range withString:@"**** **** **** "];
        
    }
    
    return newStr;
}

+ (NSString*)weakNameFrom:(NSDate*)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setFirstWeekday:2];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    
    NSUInteger weekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:date];
    switch (weekday) {
        case 1:
            return @"星期一";
            break;
        case 2:
            return @"星期二";
            break;
        case 3:
            return @"星期三";
            break;
        case 4:
            return @"星期四";
            break;
        case 5:
            return @"星期五";
            break;
        case 6:
            return @"星期六";
            break;
        case 7:
            return @"星期天";
            break;
        default:
            break;
    }
    return @"";
}
- (BOOL) isOnlyChinese
{
    NSString * chineseTest=@"^[\u4e00-\u9fa5]{0,}$";
    
    NSPredicate*chinesePredicate=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",chineseTest];
    
    return [chinesePredicate evaluateWithObject:self];
}

- (BOOL) isOnlyNumber
{
    BOOL res = YES;
    
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    
    int i = 0;
    while (i < self.length) {
        NSString * string = [self substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    
    return res;
}
- (BOOL) isValidRealName
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{2,8}$";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    
    return [predicate evaluateWithObject:self];
}
// 去掉表情
- (instancetype)removedEmojiString {
    NSMutableString* __block buffer = [NSMutableString stringWithCapacity:[self length]];
    
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                              [buffer appendString:([substring isEmoji])? @"": substring];
                          }];
    
    return buffer;
}

- (BOOL)isEmoji {
    const unichar high = [self characterAtIndex: 0];
    
    // Surrogate pair (U+1D000-1F77F)
    if (0xd800 <= high && high <= 0xdbff) {
        const unichar low = [self characterAtIndex: 1];
        const int codepoint = ((high - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000;
        
        return (0x1d000 <= codepoint && codepoint <= 0x1f77f);
        
        // Not surrogate pair (U+2100-27BF)
    } else {
        return (0x2100 <= high && high <= 0x27bf);
    }
}
@end

